<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">
        当前位置：首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品配置</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索区 -->
      <el-form
        ref="searchFormRef"
        :inline="true"
        :model="queryInfo.query"
        size="mini"
      >
        <el-form-item label="商品类别" prop="class">
          <el-select
            v-model="queryInfo.query.class"
            placeholder="请选择"
            filterable
            clearable
          >
            <el-option
              v-for="item in selectData.goods_class"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联产品" prop="product_id">
          <el-select
            v-model="queryInfo.query.product_id"
            placeholder="请选择"
            filterable
            clearable
          >
            <el-option
              v-for="item in selectData.product"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryInfo.query.status"
            placeholder="请选择"
            filterable
            clearable
          >
            <el-option key="0" label="待上架" value="0"> </el-option>
            <el-option key="1" label="已上架" value="1"> </el-option>
            <el-option key="2" label="已下架" value="2"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称" prop="keywords">
          <el-input
            v-model="queryInfo.query.keywords"
            placeholder="请输入商品名称或ID"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            class="theme-background-color"
            size="mini"
            @click="searchList"
          >
            搜索
          </el-button>
          <el-button size="mini" @click="resetSearchForm"> 重置 </el-button>
        </el-form-item>
      </el-form>

      <!-- 操作区域 -->
      <div>
        <el-button
          class="theme-background-color"
          icon="el-icon-plus"
          size="mini"
          @click="$router.push('/commodity/addCommodity')"
        >
          新增商品
        </el-button>
        <el-button
          icon="el-icon-download"
          size="mini"
          :loading="btnLoading"
          @click="downloadExcel"
        >
          导出数据
        </el-button>
      </div>

      <!-- 用户列表区域 -->
      <el-table :data="list" border stripe>
        <!-- <el-table-column label="序号" type="index"></el-table-column> -->
        <el-table-column
          label="商品名称【ID】"
          min-width="150px"
          max-width="300px"
        >
          <template slot-scope="scope">
            <el-link type="primary" @click="toDetail(scope.row.id)"
              >{{ scope.row.name }}【{{ scope.row.id }}】</el-link
            >
          </template>
        </el-table-column>
        <el-table-column label="统一价" prop="uniform_price"></el-table-column>
        <el-table-column label="商品类别" prop="class.name"></el-table-column>
        <el-table-column
          label="所属产品分类"
          prop="product_type_names"
          min-width="150px"
          max-width="300px"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column label="商品类型" prop="type.name"></el-table-column>
        <el-table-column label="状态" prop="status.name"></el-table-column>
        <el-table-column
          label="备注"
          prop="remark"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column label="操作" width="80px">
          <template slot-scope="scope">
            <el-link
              type="danger"
              v-if="scope.row.status.id == 1"
              @click="disable(scope.row)"
            >
              下架
            </el-link>
            <el-link
              type="primary"
              v-if="scope.row.status.id == 2 || scope.row.status.id == 0"
              @click="enable(scope.row.id)"
            >
              上架
            </el-link>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryInfo: {
        query: {
          class: '',
          product_id: '',
          status: '',
          keywords: ''
        },
        pagenum: 1,
        pagesize: 20
      },
      selectData: [],
      list: [],
      total: 0,
      btnLoading: false
    }
  },
  created() {
    this.getSelectData()
    this.getListData()
  },
  methods: {
    async getSelectData() {
      const { data: res } = await this.$http.post('/admin/data/find', {
        code: 'product,goods_class'
      })
      // 返回结果
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.selectData = res.data
    },
    searchList() {
      this.queryInfo.pagenum = 1
      this.getListData()
    },
    resetSearchForm() {
      //   console.log(this)
      this.$refs.searchFormRef.resetFields()
      this.getListData()
    },
    async getListData() {
      // 返回数据重命名为res
      const { data: res } = await this.$http.post(
        '/admin/goods/list',
        this.queryInfo
      )
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.list = res.data.list
      this.total = res.data.total
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getListData()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getListData()
    },
    disable(row) {
      // 弹框询问是否禁用用户
      this.$prompt('确定下架商品【' + row.name + '】吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        inputPattern: /^(?!.{500}|^\s*$)/g,
        inputErrorMessage: '请输入下架原因',
        closeOnClickModal: false
      })
        .then(async ({ value }) => {
          console.log(value)
          const { data: res } = await this.$http.post('/admin/goods/close', {
            id: row.id,
            reason: value
          })
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.$message.success(res.meta.msg)
          this.getListData()
        })
        .catch(() => {
          this.$message.info('已取消操作')
        })
    },
    async enable(id) {
      // 弹框询问是否启用用户
      const confirmResult = await this.$confirm('确定上架该商品？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消操作')
      }
      const { data: res } = await this.$http.post('/admin/goods/active', {
        id: id
      })
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getListData()
    },
    toDetail(id) {
      const newpage = this.$router.resolve({
        path: '/commodity/commodityDetail',
        query: { id: id }
      })
      window.open(newpage.href, '_blank')
    },
    async downloadExcel() {
      this.btnLoading = true
      this.$http({
        method: 'post',
        url: '/admin/Coupon/downloadExcel',
        data: this.queryInfo.query,
        headers: {
          token: window.sessionStorage.getItem('token')
        },
        responseType: 'blob'
      })
        .then((res) => {
          this.btnLoading = false
          if (res.data.type) {
            // 文件下载
            const blob = new Blob([res.data], {
              type: 'application/vnd.ms-excel'
            })
            let link = document.createElement('a')
            link.href = URL.createObjectURL(blob)
            link.setAttribute('download', '优惠券数据.xlsx')
            link.click()
            link = null
            this.$message.success('导出成功')
          } else {
            // 返回json
            this.$message.warning(res.data.msg)
          }
        })
        .catch((err) => {
          this.btnLoading = false
          this.$message.error(err)
        })
    }
  }
}
</script>

<style lang="less" scoped>
</style>
